#!/bin/bash

patch_rancher_logging_chart()
{
  local chart_dir=$1 #${CHARTS_DIR}
  local logging_version=$2 #LOGGING_VERSION
  local pkg_logging_path=$3 #${PKG_PATCH_LOGGING_PATH}
  local cwd=$(pwd)

  if [ ! -d "${pkg_logging_path}/${logging_version}" ]; then
    echo "NOTE: there is no related path: ${pkg_logging_path}/${logging_version} to patch, SKIP"
    return 0
  fi

  cd ${chart_dir}
  tar zxf rancher-logging-${logging_version}.tgz --warning=no-timestamp

  echo "patch rancher logging rke2 configmap.yaml, daemonset.yaml"
  cp -f ${pkg_logging_path}/${logging_version}/configmap.yaml ./rancher-logging/templates/loggings/rke2/configmap.yaml
  cp -f ${pkg_logging_path}/${logging_version}/daemonset.yaml ./rancher-logging/templates/loggings/rke2/daemonset.yaml
  grep "harvester-patch" ./rancher-logging/templates/loggings/rke2/configmap.yaml || true
  grep "harvester-patch" ./rancher-logging/templates/loggings/rke2/daemonset.yaml || true

  echo "patch rancher logging eventtailer"
  cp -f ${pkg_logging_path}/${logging_version}/eventtailer.yaml ./rancher-logging/templates/eventtailer.yaml
  grep "harvester-patch" ./rancher-logging/templates/eventtailer.yaml || true

  # replace fluentbit image version; yq can also work, but it strips all blank lines; use patch instead
  local valuesfile="./rancher-logging/values.yaml"
  local difffile="${pkg_logging_path}/${logging_version}/patch-vaues-fluentbit-image.diff"
  echo "patch fluentbit image version"
  echo "the current values.yaml has following fluentbit image version"
  grep "rancher/mirrored-fluent-fluent-bit" $valuesfile -1 || true
  if [ -f "$difffile" ]; then
    patch $valuesfile $difffile
  else
    echo "diff file $difffile is not found"
  fi
  echo "the patched values.yaml has following fluentbit image version"
  grep "rancher/mirrored-fluent-fluent-bit" $valuesfile -1 || true

  # remove existing chart
  rm ${chart_dir}/rancher-logging-${logging_version}.tgz

  # helm pack new
  helm package rancher-logging
  rm -rf rancher-logging
  echo "finish patch ranch-logging chart"
  cd $cwd
}

